public class TwoStringMultiply {
    public static void main(String[] args) {
//        String num1 = "2", num2 = "3";
        String num1 = "123", num2 = "456";
//        String num1 = "9", num2 = "9";
//        System.out.println(multiply(num1,num2));
        System.out.println(multiply2("99", "99"));
    }
    public static String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")){
            return "0";
        }
        String result = new String();
        int n2Index = num2.length()-1;
        while( n2Index >=0 ){
            int n1Index = num1.length()-1;
            int n2 = num2.charAt(n2Index) - '0';
            int carry = 0;
            StringBuilder temp = new StringBuilder();
            while(n1Index>=0 || carry > 0){
                int n1 = n1Index>=0 ? num1.charAt(n1Index) - '0':0;
                int mul = n1 * n2 +carry;
                temp.append(mul%10);
                carry = mul/10;
                n1Index--;
            }
            temp.reverse();
            for (int i = 0; i < num2.length() - n2Index - 1; i++) {
                temp.append("0");
            }
            /**
             * 与上一步结果相加
             */
            result =addStrings(result,temp.toString());
            n2Index--;
        }
        return result;
    }
    public static String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int numFirstIndex = num1.length()-1;
        int numSecondIndex = num2.length()-1;
        int carry = 0;
        while(numFirstIndex >=0 || numSecondIndex>=0 || carry>0){
            int left = numFirstIndex >=0 ? num1.charAt(numFirstIndex) - '0' : 0;
            int right = numSecondIndex>=0 ?num2.charAt(numSecondIndex) - '0' :0;
            int sum = left + right + carry;
            sb.append(sum%10);
            carry =sum/10;
            numFirstIndex--;
            numSecondIndex--;
        }
        return sb.reverse().toString();
    }

    public static String multiply2(String num1, String num2) {
        if ( num1.equals("0") || num2.equals("0") ) return "0";
        int[] resultArr = new int[num1.length() + num2.length()];

        // 遍历num1和num2，逐位计算乘积，填入结果数组中
        for ( int i = num1.length() - 1; i >= 0; i-- ){
            int x = num1.charAt(i) - '0';
            for ( int j = num2.length() - 1; j >= 0; j-- ){
                int y = num2.charAt(j) - '0';
                int product = x * y;
                int temp = resultArr[i+j+1] + product;
                resultArr[i+j+1] = temp % 10;
                resultArr[i+j] += temp / 10;
            }
        }
        StringBuffer result = new StringBuffer();
        int start = resultArr[0] == 0 ? 1 : 0;
        for ( int i = start; i < resultArr.length; i++ ){
            result.append(resultArr[i]);
        }
        return result.toString();
    }

}
